import request from '@/utils/request'

// 添加缓存存储
const _certificateCache = new Map()
const _CACHE_DURATION = 5 * 60 * 1000 // 缓存时间5分钟

export const certificateApi = {
  // 获取证书列表
  async getCertificates(params) {
    try {
      const response = await request({
        url: '/api/certificates',
        method: 'get',
        params
      })
      return response
    } catch (error) {
      console.error('获取证书列表失败:', error)
      throw error
    }
  },

  // 清除缓存
  clearCache() {
    _certificateCache.clear()
  },

  // 根据证书编号获取证书
  getCertificateByNumber(certNumber) {
    return request({
      url: `/api/certificates/view/${certNumber}`,
      method: 'get'
    })
  },

  // 检查证书编号是否存在
  checkCertNumber(certNumber) {
    return this.getCertificateByNumber(certNumber)
  },

  // 创建证书
  async createCertificate(data) {
    try {
      const response = await request({
        url: '/api/certificates',
        method: 'post',
        data
      })
      return response
    } catch (error) {
      console.error('创建证书失败:', error)
      throw error
    }
  },

  // 更新证书
  async updateCertificate(id, data) {
    try {
      const response = await request({
        url: `/api/certificates/${id}`,
        method: 'put',
        data
      })
      return response
    } catch (error) {
      console.error('更新证书失败:', error)
      throw error
    }
  },

  // 删除证书
  async deleteCertificate(id) {
    try {
      const response = await request({
        url: `/api/certificates/${id}`,
        method: 'delete'
      })
      return response
    } catch (error) {
      console.error('删除证书失败:', error)
      throw error
    }
  },

  // 下载二维码
  downloadQRCode(id) {
    return request({
      url: `/api/certificates/${id}/qrcode`,
      method: 'get',
      responseType: 'blob'
    })
  },

  // 批量下载二维码
  batchDownloadQRCode(ids) {
    return request({
      url: '/api/certificates/batch-download',
      method: 'post',
      data: { ids },
      responseType: 'blob'
    })
  },

  // 重新生成二维码
  regenerateQRCode(id) {
    return request({
      url: `/api/certificates/${id}/regenerate-qrcode`,
      method: 'post',
      headers: {
        'Content-Type': 'application/json'
      }
    })
  },

  // 切换证书状态
  toggleCertificateStatus(id) {
    return request({
      url: `/api/certificates/${id}/toggle-status`,
      method: 'patch'
    })
  }
}

// 切换证书状态
export const toggleCertificateStatus = id => {
  return request({
    url: `/api/certificates/${id}/toggle-status`,
    method: 'patch'
  })
}
